package com.app.bussinesslocator.httpclient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;



import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

public class MyHttpClient extends Observable{
	// khai bao duong dan api chung
	private static final String BASE_URL = "http://www.techbusters.net.au";
	// string url;
	private static final String SEARCH = "/api";
	// khai bao context
	private Context mContext;
	
	
	HttpClient httpClient = new DefaultHttpClient();
	HttpPost httpPost ;
	
	
	public MyHttpClient(Context context, Observer observer) {
		addObserver(observer);
		mContext = context;
	}
	
	
	private class HttpTask extends AsyncTask<Object, Void, Object> {
		private static final int URL_API = 0x0;
		private static final int NAME_VALUE_PAIR = 0x1;
		private static final String TAG = "HttpPostTask";

		@Override
		protected Object doInBackground(Object... params) {
			String urlApi = (String) params[URL_API];
			List<BasicNameValuePair> nameValuePair = null;
			try {
				Log.i("HttpTask", "------------2");
				nameValuePair = (ArrayList<BasicNameValuePair>) params[NAME_VALUE_PAIR];
			} catch (Exception e) {
				
			}
			
			if(nameValuePair==null) {
				Log.i("HttpTask", "------------3");
				nameValuePair = new ArrayList<BasicNameValuePair>();
			}
			
			HttpParams httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters, 6000);
			HttpClient httpClient = new DefaultHttpClient(httpParameters);
			httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
			Object result = null;
			try{
			//For dev
			Log.i("HttpTask", "\n\n");
			Log.i("HttpTask", "==== begin post method ====");
			Log.i("HttpTask", "HOST: "+urlApi);
			String urlGet = urlApi;
			for (int i = 0; i < nameValuePair.size(); i++) {
				BasicNameValuePair b = nameValuePair.get(i);
				if(i==0) urlGet+="?"+b.getName()+"="+b.getValue();
				else urlGet+="&"+b.getName()+"="+b.getValue();
				Log.i("HttpTask", b.getName()+"="+b.getValue());
			}
			Log.i("HttpTask", "URL GET: "+urlGet);
			Log.i("HttpTask", "==== end post method ====");
			Log.i("HttpTask", "\n\n");
			HttpPost httpPost = null;
			HttpResponse response = null;
			try {
				Log.i("HttpTask", "------------4");
				httpPost = new HttpPost(urlApi);
				httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
				response = httpClient.execute(httpPost);
			} catch (Exception e) {
				Log.i("HttpTask", "------------5");
				e.printStackTrace();
				return null;
			}
			Log.d(TAG, "-- Request URL: " + urlApi);
			int statusCode = 0;
			try {
				Log.i("HttpTask", "------------6");
				statusCode = response.getStatusLine().getStatusCode();
			} catch (Exception e) {
				Log.i("HttpTask", "------------7");
				e.printStackTrace();
				return null;
			}
			
			Log.e(TAG, "HttpClient status code: " + statusCode);
			if (statusCode != HttpStatus.SC_OK) {
				Log.i("HttpTask", "------------8");
				Log.e(TAG, "HttpClient Executive Error: " + statusCode);
				if ((statusCode == 0) || (statusCode == 500) ) {
					Log.i("HttpTask", "------------9");
					Log.i("Thientv", "Khong ket noi duoc voi server");
					try {
						Log.i("HttpTask", "------------10");
						((Activity)mContext).runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								Toast.makeText(mContext, "Không kết nối được với server...", Toast.LENGTH_LONG).show();Toast.makeText(mContext, "Hệ thống đang cập nhập...", Toast.LENGTH_LONG).show();
							}
						});
					} catch (Exception e) {
						Log.i("HttpTask", "------------11");
						e.printStackTrace();
					}
				} else {
					Log.i("HttpTask", "------------12");
				}
				return null;
			}
			HttpEntity entity = response.getEntity();
			Log.i("HttpTask", "------------13");
			if (entity != null) {
				Log.i("HttpTask", "------------14");
				try {
					Log.i("HttpTask", "------------15");
					result = DataJsonParser.getInstance().parse(entity.getContent());
					Log.i("HttpTask", "------------16");
				} finally {
					entity.consumeContent();
					Log.i("HttpTask", "------------17");
				}
			}
		} catch (ClientProtocolException e) {
			Log.e(TAG, e.toString());
		} catch (IOException e) {
			Log.e(TAG, e.toString());
		} catch (Exception e) {
			e.printStackTrace();
			Log.i("Thientv", "===============");
			try {
				((Activity)mContext).runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
//						Toast.makeText(mContext, "Không kết nối được với server...", Toast.LENGTH_LONG).show();Toast.makeText(mContext, "Hệ thống đang cập nhập...", Toast.LENGTH_LONG).show();
					}
				});
			} catch (Exception f) {
				f.printStackTrace();
			}				// Check loi khong ket noi duoc voi server o day 
		}
		return result;
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			setChanged();
			notifyObservers(result);
		}
	}
	
	
	void search(String keyword, int pageNumber, float lon, float lat){
		httpPost = new HttpPost(BASE_URL+SEARCH);
		 try {
		        // Add your data
		        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		        nameValuePairs.add(new BasicNameValuePair("keyword", keyword));
		        nameValuePairs.add(new BasicNameValuePair("page_number", "0"));
		        nameValuePairs.add(new BasicNameValuePair("latitude", String.valueOf(lon)));
		        nameValuePairs.add(new BasicNameValuePair("longitude", String.valueOf(lat)));
		        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

		        // Execute HTTP Post Request
		        HttpResponse response = httpClient.execute(httpPost);
		        
		        int reponseCode = response.getStatusLine().getStatusCode();
		        switch (reponseCode) {
				case 200:
					HttpEntity entity = response.getEntity();
					if(entity != null)
					 {
						String responseBody = EntityUtils.toString(entity);
						Log.i("DATA", "RECIVED: "+responseBody);
					 }
					break;

				default:
					break;
				}
		        
		        
		        
		    } catch (ClientProtocolException e) {
		        // TODO Auto-generated catch block
		    } catch (IOException e) {
		        // TODO Auto-generated catch block
		    }
	}
	
		public void searchKey(String keyword, int pageNumber, float lon, float lat) {
			String url = BASE_URL + SEARCH;
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			params.add(new BasicNameValuePair("keyword", keyword));
			params.add(new BasicNameValuePair("page_number", "0"));
			params.add(new BasicNameValuePair("latitude", String.valueOf(lon)));
			params.add(new BasicNameValuePair("longitude", String.valueOf(lat)));
			android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY);
			HttpTask httpTask = new HttpTask();
			if (Build.VERSION.SDK_INT >= 11)
				httpTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url, params);
			else
				httpTask.execute(url, params);
		}
}
